import inspect
import zmq
import sys
sys.path.append("./")
from utils import *

DEAULT_VALUE="ANY"

class Http(object):
	SIP=DEAULT_VALUE
	DIP=DEAULT_VALUE
	SPORT=DEAULT_VALUE
	DPORT=DEAULT_VALUE
	URI=DEAULT_VALUE
	METHOD=DEAULT_VALUE
	TIME=DEAULT_VALUE
	USER=DEAULT_VALUE
"""
general classes
"""
class exceptions(Exception):
        class InvaildArgsLen(Exception):
                args="Error:InvaildArgsLen"

op=["=","!=","<",">","<=",">=","in","!in"]

class Effect(object):
	ALLOW=1
	DENY=0

class Condition(object):
	"key op value"

		
class Policy(object):
	GROUP=DEAULT_VALUE
	TIME=DEAULT_VALUE
	OWNER=DEAULT_VALUE
	def __init__(self):
		self.rules=[]
		self.context=zmq.Context()
		self.container=self.context.socket(zmq.DEALER)
		self.container.connect("tcp://localhost:5556")
		pass

	def add(self,rule):
		self.rules.append(rule)
		pass

	def submit(self):
		res=[]
		for i in self.rules:
			res.append(str(i))
		msg={}
		msg[MSG_TYPE]=TYPE_POLICY_PUT
		msg[MSG_SENDER]="test"
		msg[MSG_BODY]={}
		msg[MSG_BODY]["POLICY"]=res
		msg[MSG_BODY]["APPID"]="ALL"
		msg[MSG_BODY]["GROUPID"]=0
		msg[MSG_BODY]["GUARDID"]="ALL"
		self.container.send(json.dumps(msg))

class Rule(object):
	GROUP=DEAULT_VALUE
	TIME=DEAULT_VALUE
	OWNER=DEAULT_VALUE
	PRINCIPLE=DEAULT_VALUE
	ACTION=DEAULT_VALUE
	EFFECT=Effect.DENY
	TARGET=DEAULT_VALUE
	CONDITION={}

	def add(self,attr,*args):
		t=inspect.stack()[-2][-2][0]
		attr=t[t.find("(")+1:t.find(")")]
		attr=attr.split(",")[0].split(".")[1]
		op=args[0]
		value=args[1]
		if Rule.PRINCIPLE==DEAULT_VALUE:
			Rule.PRINCIPLE=[]
			Rule.PRINCIPLE.append(attr)
		else:
			Rule.PRINCIPLE.append(attr)
		Rule.PRINCIPLE=list(set(Rule.PRINCIPLE))
		Rule.CONDITION[attr]=(op,value)

	def __str__(self):
		members = [attr for attr in dir(Rule()) if not callable(attr) and not attr.startswith("__") and attr!="add"]
		res={}
		for m in members:
			res[m]=getattr(self,m)
		return str(res)





		

